package spar.cancer.data.from.ecxt;

import spar.cancer.Cancer;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class EcxtCSV extends EcxtAbstract {
    private final String fileName;
    private final List<String> lines;
    private final Map<String, Integer> varsName = new HashMap<>();
    private int lineIndex;

    public EcxtCSV(String fileName) throws IOException {
        this.fileName = fileName;
        this.lines = Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8);
        this.lineIndex = 1;
    }

    public EcxtCSV(List<Cancer<Double>> objs, String fileName) throws IOException {
        this(fileName);
        bind(objs);
    }

    @Override
    public void bind(List<Cancer<Double>> objs) {
        Cancer.setECxtObjs(objs);
        String[] names = lines.get(0).split(",");
        objs.forEach(obj -> {
            for (int i = 0; i < names.length; i++) {
                if (names[i].equals(obj.getName())) {
                    varsName.put(obj.getName(),i);
                    break;
                }
            }
        });
    }

    @Override
    public Map<String, Double> getNextData() {
        Map<String, Double> ret = new HashMap<>();
        String[] vals = lines.get(lineIndex).split(",");
        varsName.forEach((name, index) -> {
            ret.put(name, Double.valueOf(vals[index]));
        });
        lineIndex++;
        return ret;
    }

    public boolean hasNextData() {
        iterExit();
        boolean hasNextDataFlag = lineIndex < lines.size();
        iterEntry(hasNextDataFlag);
        return hasNextDataFlag;
    }

    @Override
    public void close() {

    }
}
